"use strict";
const Service = require("egg").Service;
const jwt = require("jsonwebtoken");
class UserOrderService extends Service {
    get UserOrder() {
        return this.app.model.UserOrder;
    }
    get Order() {
        return this.app.model.Order;
    }
    async join({ orderId, userId, sex }) {
        const user = await this.UserOrder.findOne({ user: userId });
        let order = await this.Order.findById(orderId);
        if (user) {
            if (user.orders.includes(orderId)) {
                this.ctx.throw(500, "不能重复加入")
            } else {
                await this.UserOrder.findOneAndUpdate({ user: userId }, { orders: [...user.orders, orderId] })
                order.persons.push({ nickName: "chenzhaozhao", id: userId, sex });
            }
        } else {
            await this.UserOrder({ user: userId, orders: [orderId] }).save();
            order.persons.push({ nickName: "chenzhaozhao", id: userId, sex });
        }
        await this.Order.findByIdAndUpdate(orderId, { persons: order.persons });
        return Promise.resolve({ success: 1 });
    }
    async quit({ orderId, userId}) {
       const user= await this.UserOrder.findOne({user:userId});
       const order= await this.Order.findById(orderId)
       if(user){
         await  this.UserOrder.findOneAndUpdate({user:userId},{orders:user.orders.filter(id=>id.toString()!==orderId.toString())})
         await  this.Order.findByIdAndUpdate(orderId,{persons:order.persons.filter(person=>person.id.toString()!==userId.toString())})
         return Promise.resolve({success:1})
       }else{

       }
    }
}
module.exports = UserOrderService;
